package indi.wshape1.takeawaydeliveryinfo.servlet;

import indi.wshape1.takeawaydeliveryinfo.service.UtilService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author Wshape1
 * @create 2022-11-07 18:50
 */

@WebServlet(name = "LoginServlet", value = {"/login"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        int state = 0;  // -1 - 验证码错误  0 - 账号或密码错误   1 - 已有登录   2 - 成功

        String key = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        if (!key.equalsIgnoreCase(req.getParameter("inputVerifyCode"))) {
            state = -1;
            writer.print(state);
            return;
        }

        String type = req.getParameter("type");
        String user = req.getParameter("user");
        String pwd = req.getParameter("pwd");

        if (req.getServletContext().getAttribute(user) != null || req.getSession().getAttribute("user") != null) {
            state = 1;
        } else {

            if ("sender".equals(type) && UtilService.loginSender(user, pwd)) {
                state = 2;
            } else if ("admin".equals(type) && UtilService.loginAdmin(user, pwd)) {
                state = 2;
            } else if ("root".equals(type) && UtilService.loginRoot(user, pwd)) {
                state = 2;
            }
            if (state == 2) {
                req.getServletContext().setAttribute(user, type);
                req.getSession().setAttribute("user", user);
            }

            //  免登录 addCookie
            if (state == 2 && "true".equals(req.getParameter("noLogin"))) {
                Cookie noLogin = new Cookie("noLogin", type + ":" + user + ":" + pwd);
                noLogin.setMaxAge(60 * 60 * 24 * 3);
                noLogin.setPath("/");
                resp.addCookie(noLogin);
            }

        }

        writer.print(state);

    }

}
